// 1.创建store对象 存储默认状态
// 2.将store对象放在一个全局的组件可以够到的地方
// 3.让组件获取store对象中的状态 并将状态显示在组件中
import { action, makeObservable, observable, configure, runInAction, computed, autorun } from 'mobx'
import axios from 'axios'
// 严格模式
configure({enforceActions: 'observed'})
class CounterStore {
  constructor(){
    // 6以后新增的方式 还有一个makeAutoObservable 可以省去 observable action 等装饰器
    makeObservable(this)
    autorun(() => {
      try{
        uniqueUsername(this.username)
        console.log('用户名可用')
      }catch(error){
        console.log(error)
      }
    }, {
      delay: 1500
    })
  }

  @observable count = 0
  @observable users = []
  @observable username = ''

  @action.bound increment() {
    this.count = this.count + 1
  }

  @action decrement = () => {
    this.count = this.count - 1
  }
  
  @action  getData = async() => {
    const { data } = await axios.get('https://api.github.com/users')
    // runInAction(() => this.users = data)
    this.users = data
  }

  @computed get getResult(){
    return this.count * 10
  }

  @action.bound changeUsername(username) {
    this.username = username
  }

}

function uniqueUsername(username) {
  return new Promise((resolve, reject) => {
    if(username === 'admin'){
      reject('用户名已经存在')
    }else {
      resolve()
    }
  })
}

const counter = new CounterStore()

export default counter